from rest_framework import serializers
import re
from meiduo_mall.utils.qq_sdk import OAuthQQ
from .models import OAuthQQUser
from users.models import User
from meiduo_mall.utils import jwt_token


class OAuthQQUserSerializer(serializers.Serializer):

    # 定义属性：接收值
    mobile = serializers.CharField(write_only=True)
    password = serializers.CharField(write_only=True)

    sms_code = serializers.IntegerField(write_only=True)
    access_token = serializers.CharField(write_only=True)
    # 定义属性：输出值
    user_id =serializers.IntegerField(read_only=True)
    username=serializers.CharField(read_only=True)
    token=serializers.CharField(read_only=True)
    # 定义验证方法
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号错误')
            # 当前是绑定，而不是注册，不需要判断手机号存在，如果手机号存在，表示与现有帐号绑定
        return value

    def validate_access_token(self, value):
        openid = OAuthQQ.check_openid_token(value)
        if openid is None:
            raise serializers.ValidationError('身份信息无效')
        return openid

    def validate(self, attrs):
        # 验证短信验证码
        return attrs

    # 创建或修改 方法
    def create(self, validated_data):
        mobile = validated_data.get('mobile')
        password = validated_data.get('password')
        openid = validated_data.get('access_token')
        # 3.根据手机号查询对象
        try:
            user=User.objects.get(mobile=mobile)
        except:
            # 4.如果不存在则新建对象并绑定
            # 4.1创建新用户对象
            user = User()
            user.mobile = mobile
            user.username = mobile
            user.set_password(password)
            user.save()
            # 4.2创建绑定对象
            oauthqqUser = OAuthQQUser()
            # 给对象赋值
            oauthqqUser.openid = openid
            oauthqqUser.user = user
            oauthqqUser.save()
            # 4.3响应
            user.token = jwt_token.get_token(user)
            return user

        else:
            # 5.如果已经存在则判断手机号是否存正确

            if not user.check_password(password):
                # 7.如果不正确则返回错误
                raise serializers.ValidationError('帐号密码错误')
            # 6.如果正确则绑定
            oauthqqUser = OAuthQQUser()
            oauthqqUser.openid = openid
            oauthqqUser.user = user
            oauthqqUser.save()
            # 4.3响应
            user.token = jwt_token.get_token(user)
            return user
